# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 2019

@author: 01373604
"""

import pickle
import sys
import os
import json
import traceback
from flask import Flask
from flask import request
from  data_handle.data_handle_inference import data_handle_inference,model_inference
from data_handle.just_mask import mask_matrix
from tensorflow.contrib import keras as K
import util.logger as FCLogger
sys.path.append(os.path.dirname(__file__))
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

app = Flask(__name__)



@app.route('/', methods=['get'])
def hello_world():
    return 'Hello, world!'


@app.route('/healthCheck')
def healthCheck():
    tmp_json = {}
    tmp_json['code'] = 0
    tmp_json['message'] = 'servicestart'
    FCLogger.healthLog.info("services alive")
    return json.dumps(tmp_json)


@app.route('/call_model', methods=['POST', 'GET'])
def call_model():
    if request.method == 'GET':
        FCLogger.postLog.info("Method GET")
        return 'Get Model!'
    elif request.method == 'POST':
        # 接收数据
        try:
            FCLogger.postLog.info("Method POST")    # 不正常接口返回信息
            online_json_raw = request.get_json()
            FCLogger.postLog.info("Request get_json")
        except:
            FCLogger.postLog.error("Get Json data fail")
            FCLogger.postLog.error(traceback.format_exc())
            fail_type = {}
            fail_type['FailType'] = "Get Json data fail"
            fail_type = json.dumps(fail_type)
            return fail_type

        # 调用模型
        try:
            json_data_raw = online_json_raw
            """
            语义分析模型调用及结果整理部分
            """
            x_inference = data_handle_inference(json_data_raw, word_enc, word_set)
            intent_output, subtask_output, subtask_detail_output = \
                model_inference(model,x_inference,
                                mask_matrix_ins.sub_mask,
                                mask_matrix_ins.detail_mask,
                                threshold = 0.15)



            result = [{"predict_task":"intent","predict_value":"业务咨询"}]
            return result
        except:
            FCLogger.postLog.error("Run model fail")
            FCLogger.postLog.error(traceback.format_exc())
            fail_type = {}
            fail_type['FailType'] = "Run model fail"
            fail_type = json.dumps(fail_type)
            return fail_type

    else:
        fail_type = {}
        fail_type['FailType'] = "Request type fail"
        fail_type = json.dumps(fail_type)
        return fail_type
        # 返回异常的格式






if __name__ == '__main__':

    mask_matrix_ins = mask_matrix()

    with open("data/Intermediate_data/word_label.pkl", 'rb') as f:
        word_enc = pickle.load(f)

    word_set = set(word_enc.classes_)
    model = K.models.load_model("data/model_path/nlp_class_ori.h5",compile=False)
    model._make_predict_function()
    app.run(host='0.0.0.0', port=8080, debug=True)